package faf.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.view.RedirectView;

import faf.business.SheetManager;
import faf.business.SurveyManager;
import faf.business.UserManager;
import faf.entities.Account;
import faf.entities.Sheet;
import faf.entities.Survey;

public class LandingController implements Controller {
	UserManager userManager;
	SheetManager sheetManager;
	SurveyManager surveyManager;
	
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public void setSheetManager(SheetManager sheetManager) {
		this.sheetManager = sheetManager;
	}
	
	public void setSurveyManager(SurveyManager surveyManager) {
		this.surveyManager = surveyManager;
	}
	
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		Account account = userManager.login(request.getParameter("token"));
		if(account == null){
			return new ModelAndView("landing");
		} else {
			request.getSession().setAttribute("user", account);
			if(request.getParameter("sheet") != null){
				Sheet sheet = sheetManager.get( Long.parseLong(request.getParameter("sheet")) );
				Survey s = sheet.getSurvey();
				request.setAttribute("questions", s.getQuestionList());
				return new ModelAndView(new RedirectView("sheet.htm?id="+request.getParameter("sheet")));
			
			}
		}
		return new ModelAndView("home");
	}


}
